<template>
  <view class="container">
    <template v-if="formData.dates.length > 0">
      <view class="content-wrapper">
        <!-- 表单内容 -->
        <template v-if="formData.dates.length > 0 && currentForm">
          <uv-gap height="10"></uv-gap>
          <uv-form
            :key="currentDateIndex"
            ref="formRef"
            :model="currentForm"
            :rules="formRules"
            labelPosition="left"
            labelWidth="160"
            borderBottom
          >
            <!-- 客户信息 -->
            <view class="form-card">
              <view class="card-title">
                <view class="icon-wrapper">
                  <uv-icon name="account" size="28" color="#2979ff"></uv-icon>
                </view>
                <text>客户信息</text>
              </view>
              <uv-cell-group>
                <uv-form-item label="客户姓名" prop="customer_name" borderBottom required>
                  <uv-input
                    v-model="currentForm.customer_name"
                    placeholder="请输入客户姓名"
                    border="none"
                    clearable
                  ></uv-input>
                </uv-form-item>

                <uv-form-item label="客户电话" prop="customer_phone" borderBottom>
                  <uv-input
                    v-model="currentForm.customer_phone"
                    placeholder="请输入客户电话"
                    border="none"
                    clearable
                  ></uv-input>
                </uv-form-item>
              </uv-cell-group>
            </view>

            <template v-if="onLoadOption?.type === 'add' && formData.dates.length > 0">
              <!-- 日期选择区域 -->
              <view class="date-select-area">
                <view class="date-info">
                  <text class="date-label">已选日期</text>
                  <text class="date-count" v-if="formData.dates.length"
                    >{{ formData.dates.length }}天</text
                  >
                </view>
                <uv-button
                  @click="eventDateHandle('open')"
                  text="选择日期"
                  type="primary"
                  size="small"
                  :custom-style="{
                    borderRadius: '50rpx',
                    width: '200rpx',
                    height: '70rpx',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    boxShadow: '0 4rpx 16rpx rgba(41, 121, 255, 0.2)',
                  }"
                >
                  <template #default>
                    <view class="button-content">
                      <uv-icon
                        name="calendar"
                        size="24"
                        color="#fff"
                        style="margin-right: 6rpx"
                      ></uv-icon>
                      <text>选择日期</text>
                    </view>
                  </template>
                </uv-button>
              </view>

              <!-- 日期切换标签 -->
              <uv-sticky bgColor="#fff" offsetTop="-10">
                <view class="tabs-wrapper">
                  <uv-tabs
                    :lineWidth="80"
                    :list="formData.dates"
                    @change="(item) => eventDateHandle('tabsChange', item)"
                  ></uv-tabs>
                </view>
              </uv-sticky>
            </template>
            <template v-if="onLoadOption?.type === 'details'"> </template>
            <!-- 基本信息 -->
            <view class="form-card">
              <view class="card-title">
                <view class="icon-wrapper">
                  <uv-icon name="car" size="28" color="#2979ff"></uv-icon>
                </view>
                <text>基本信息</text>
              </view>
              <uv-cell-group>
                <uv-form-item label="车号" prop="vehicle_number" borderBottom>
                  <uv-input
                    v-model="currentForm.vehicle_number"
                    placeholder="请输入车号"
                    border="none"
                    clearable
                  ></uv-input>
                </uv-form-item>

                <uv-form-item label="送货目的地" prop="delivery_destination" borderBottom>
                  <uv-input
                    v-model="currentForm.delivery_destination"
                    placeholder="请输入送货目的地"
                    border="none"
                    clearable
                  ></uv-input>
                </uv-form-item>
              </uv-cell-group>
            </view>
            <!-- 产品信息 -->
            <view class="form-card">
              <view class="card-title">
                <view class="icon-wrapper">
                  <uv-icon name="gift" size="28" color="#2979ff"></uv-icon>
                </view>
                <text>产品信息</text>
              </view>

              <uv-cell-group>
                <uv-form-item label="产品" prop="stock_ids" borderBottom required>
                  <view
                    class="spec-selector"
                    @click="eventDateHandle('pickerStockIdsOpen')"
                  >
                    <text v-if="currentForm.stock_name">{{
                      currentForm.stock_name
                    }}</text>
                    <text v-else class="placeholder">请选择产品</text>
                    <uv-icon name="arrow-right" size="16" color="#999"></uv-icon>
                  </view>
                  <uv-picker
                    ref="pickerRef"
                    :columns="[manufacturerGroupList]"
                    keyName="label"
                    @confirm="(e) => eventDateHandle('pickerStockIdsConfirm', e)"
                    @cancel="(e) => eventDateHandle('pickerStockIdsCancel', e)"
                    :show-toolbar="true"
                    title="选择产品"
                  >
                  </uv-picker>
                </uv-form-item>
                <uv-form-item label="规格型号" prop="product_spec" borderBottom>
                  <!-- <view
                    class="spec-selector"
                    @click="eventDateHandle('pickerProductSpecOpen')"
                  >
                    <text v-if="currentForm.product_spec">{{
                      currentForm.product_spec
                    }}</text>
                    <text v-else class="placeholder">请选择规格型号</text>
                    <uv-icon name="arrow-right" size="16" color="#999"></uv-icon>
                  </view>
                  <uv-picker
                    ref="pickerRef"
                    :columns="[specifications]"
                    @confirm="(e) => eventDateHandle('pickerProductSpecConfirm', e)"
                    @cancel="(e) => eventDateHandle('pickerProductSpecCancel', e)"
                    :show-toolbar="true"
                    title="选择规格型号"
                  >
                  </uv-picker> -->
                  <uv-input
                    v-model="currentForm.product_spec"
                    border="none"
                    disabled
                    clearable
                  ></uv-input>
                </uv-form-item>

                <uv-form-item label="单位" prop="unit" borderBottom>
                  <uv-input
                    v-model="currentForm.unit"
                    border="none"
                    disabled
                    clearable
                  ></uv-input>
                </uv-form-item>
              </uv-cell-group>
            </view>
            <!-- 价格信息 -->
            <view class="form-card">
              <view class="card-title">
                <view class="icon-wrapper">
                  <uv-icon name="bell" size="28" color="#2979ff"></uv-icon>
                </view>
                <text>价格信息</text>
              </view>
              <!-- 添加库存使用统计显示 -->
              <view class="stock-usage-info" v-if="currentForm.stock_name">
                <view class="stock-usage-item">
                  <text class="label">当前产品：</text>
                  <text class="value"
                    >{{ currentForm.stock_name }} {{ currentForm.product_spec }}</text
                  >
                </view>
                <view class="stock-usage-item">
                  <text class="label">总库存：</text>
                  <text class="value"
                    >{{ getCurrentStockInfo?.totalStock || 0
                    }}{{ currentForm.unit }}</text
                  >
                </view>
                <view class="stock-usage-item">
                  <text class="label">已使用：</text>
                  <text class="value" :class="{ warning: getCurrentStockInfo?.used > 0 }">
                    {{ getCurrentStockInfo?.used || 0 }}{{ currentForm.unit }}
                  </text>
                </view>
                <view class="stock-usage-item">
                  <text class="label">剩余可用：</text>
                  <text
                    class="value"
                    :class="{ danger: getCurrentStockInfo?.remaining <= 0 }"
                  >
                    {{ getCurrentStockInfo?.remaining || 0 }}{{ currentForm.unit }}
                  </text>
                </view>
              </view>
              <uv-cell-group>
                <uv-form-item :label="`数量`" prop="quantity" borderBottom required>
                  <uv-input
                    v-model="currentForm.quantity"
                    type="number"
                    :placeholder="!currentForm.stock_name ? `请选择产品` : `请输入数量`"
                    :disabled="!currentForm.stock_name"
                    border="none"
                    :max="availableStock || 0"
                    clearable
                    @input="calculateAmounts"
                  >
                    <template #suffix>
                      <text class="input-suffix">{{
                        currentForm.unit || defaultUnit
                      }}</text>
                    </template>
                  </uv-input>
                </uv-form-item>

                <uv-form-item label="单个售价" prop="unit_price" borderBottom required>
                  <uv-input
                    v-model="currentForm.unit_price"
                    type="number"
                    :placeholder="!currentForm.stock_name ? `请选择产品` : `请输入售价`"
                    :disabled="!currentForm.stock_name"
                    border="none"
                    clearable
                    @input="calculateAmounts"
                  >
                    <template #prefix>
                      <text class="input-prefix">¥</text>
                    </template>
                  </uv-input>
                </uv-form-item>

                <uv-form-item label="单个进价" prop="cost_price" borderBottom>
                  <uv-input
                    v-model="currentForm.cost_price"
                    type="number"
                    :placeholder="!currentForm.stock_name ? `请选择产品` : `请输入进价`"
                    :disabled="!currentForm.stock_name"
                    border="none"
                    clearable
                    @input="calculateAmounts"
                  >
                    <template #prefix>
                      <text class="input-prefix">¥</text>
                    </template>
                  </uv-input>
                </uv-form-item>

                <uv-form-item label="总金额" borderBottom>
                  <uv-input
                    v-model="currentForm.amount"
                    disabled
                    :placeholder="currentForm.amount || '总金额 = 销价 × 数量'"
                    border="none"
                  >
                    <template #prefix>
                      <text class="input-prefix">¥</text>
                    </template>
                  </uv-input>
                </uv-form-item>

                <uv-form-item label="净利润" borderBottom>
                  <uv-input
                    v-model="currentForm.net_profit"
                    disabled
                    :placeholder="
                      currentForm.net_profit || '净利润 = (销价 - 进价) × 数量'
                    "
                    border="none"
                  >
                    <template #prefix>
                      <text class="input-prefix">¥</text>
                    </template>
                  </uv-input>
                </uv-form-item>

                <!-- 首付金额 -->
                <uv-form-item
                  v-if="currentForm.status === 0"
                  label="首付金额"
                  prop="paid_amount"
                  borderBottom
                >
                  <uv-input
                    v-model="currentForm.paid_amount"
                    type="number"
                    placeholder="请输入首付金额"
                    border="none"
                    clearable
                    @input="calculateRemaining"
                  >
                    <template #prefix>
                      <text class="input-prefix">¥</text>
                    </template>
                  </uv-input>
                </uv-form-item>
                <!-- 支付状态开关 -->
                <view class="payment-status">
                  <uv-form-item label="是否汇款" prop="status" borderBottom>
                    <uv-switch
                      v-model="currentForm.status"
                      @change="handlePaymentStatusChange"
                      activeColor="#2979ff"
                      :active-value="2"
                      :inactive-value="0"
                    ></uv-switch>
                  </uv-form-item>
                </view>
              </uv-cell-group>
            </view>

            <!-- 金额汇总 -->
            <template v-if="currentForm.status === 0">
              <view class="form-card summary-card">
                <uv-cell-group>
                  <uv-cell
                    :title="'订单总额'"
                    :value="'¥' + (currentForm.amount || '0.00')"
                    :titleStyle="{ color: '#666', fontSize: '28rpx' }"
                    :valueStyle="{
                      color: '#2979ff',
                      fontSize: '32rpx',
                      fontWeight: '500',
                    }"
                  >
                  </uv-cell>
                  <uv-cell
                    v-if="currentForm.paid_amount"
                    :title="'已付金额'"
                    :value="'¥' + currentForm.paid_amount"
                    :titleStyle="{ color: '#666', fontSize: '28rpx' }"
                    :valueStyle="{
                      color: '#19be6b',
                      fontSize: '32rpx',
                      fontWeight: '500',
                    }"
                  >
                  </uv-cell>
                  <uv-cell
                    v-if="currentForm.paid_amount"
                    :title="'剩余金额'"
                    :value="'¥' + remainingAmount"
                    :titleStyle="{ color: '#666', fontSize: '28rpx' }"
                    :valueStyle="{
                      color: '#ff4d4f',
                      fontSize: '32rpx',
                      fontWeight: '500',
                    }"
                  >
                  </uv-cell>
                </uv-cell-group>
              </view>
            </template>
          </uv-form>
        </template>
      </view>
      <!-- 底部按钮 -->
      <view class="footer-buttons">
        <view class="button-group">
          <view class="button-wrapper" :style="{ paddingRight: isEdit ? '24rpx' : '0' }">
            <uv-button
              v-if="isEdit"
              type="error"
              text="撤销订单"
              @click="eventDateHandle('handleDelete')"
              :customStyle="{
                borderRadius: '12rpx',
              }"
            ></uv-button>
          </view>
          <view class="button-wrapper" :style="{ paddingLeft: isEdit ? '24rpx' : '0' }">
            <uv-button
              type="primary"
              :text="isEdit ? '保存修改' : '提交订单'"
              @click="eventDateHandle('handleSubmit')"
              :loading="isSubmitting"
              :customStyle="{
                borderRadius: '12rpx',
              }"
            ></uv-button>
          </view>
        </view>
      </view>
      <!-- 确认弹窗 -->
      <uv-modal
        ref="modal"
        :title="modalConfig.title"
        :content="modalConfig.content"
        :show-cancel-button="true"
        confirm-color="#2979ff"
        @confirm="handleModalConfirm"
      ></uv-modal>
    </template>

    <view
      v-if="onLoadOption?.type === 'add' && formData.dates.length == 0"
      class="add-icon"
      @click="eventDateHandle('open')"
    >
      <view class="add-content">
        <view class="icon-wrapper">
          <uv-icon name="plus" color="#2979ff" size="36"></uv-icon>
        </view>
        <text class="add-text">点击选择日期</text>
      </view>
    </view>
    <uv-calendar
      ref="calendar"
      :insert="false"
      mode="multiple"
      :show-lunar="false"
      :closeOnClickOverlay="false"
      :range-color="themeColor"
      :active-date="dates"
      @confirm="(e) => eventDateHandle('confirm', e)"
    />
    <!-- 提示组件 -->
    <uv-toast ref="toast"></uv-toast>
    <uv-notify ref="notify"></uv-notify>
  </view>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, nextTick } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { getEmptyForm, themeColor, defaultUnit } from "@/utils/outStockUtils";
import cloudConfig from "@/config/uniCloudConfig.js";
// const uniCloudSalesManager = uniCloud.importObject("outStockManager"); //销售表
const uniCloudSalesManager = cloudConfig.getCloudObject("outStockManager");
const uniCloudStockManager = cloudConfig.getCloudObject("inStockManager");
// const uniCloudSalesManager = uniCloud.importObject('outStockManager', {
// 	customUI: true, // 重要: 指定为线上云对象
// 	 endpoint: config.uniCloudUrl, // 线上云环境地址
// });

// 组件引用
const formRef = ref(null);
const calendar = ref(null);
const modal = ref(null);
const toast = ref(null);
const notify = ref(null);
const pickerRef = ref(null);
// 状态管理
const isEdit = ref(false);
const isSubmitting = ref(false);
const currentDateIndex = ref(0);
const onLoadOption = ref(null);
const manufacturerGroupList = ref([]);

// 添加库存跟踪 Map
const stockUsageMap = ref(new Map());
// 规格列表

const specifications = ["325", "325R", "425", "425R"];
// 表单数据
const formData = ref({
  dates: [],
  forms: [],
});
// 添加计算属性用于显示实际可用库存
// const availableStock = computed(() => {
//   if (!currentForm.value?.stock_name || !currentForm.value?.product_spec) {
//     return 0;
//   }

//   // 获取原始库存
//   const originalStock = manufacturerGroupList.value.find(
//     (item) =>
//       item.manufacturer === currentForm.value.stock_name &&
//       item.specification === currentForm.value.product_spec
//   );

//   if (!originalStock) return 0;

//   // 计算所有日期中相同产品和规格的总使用量（不包括当前表单）
//   const totalUsedQuantity = formData.value.forms.reduce((sum, form) => {
//     if (
//       form.stock_name === currentForm.value.stock_name &&
//       form.product_spec === currentForm.value.product_spec
//     ) {
//       return sum + (Number(form.quantity) || 0);
//     }
//     return sum;
//   }, 0);

//   // 减去当前表单的数量，以便正确显示可用库存
//   const currentQuantity = Number(currentForm.value.quantity) || 0;
//   const availableQuantity =
//     originalStock.totalRemainingQuantity - (totalUsedQuantity - currentQuantity);

//   return availableQuantity;
// });

// // 添加监听器实时更新库存显示
// watch(
//   () => [
//     currentForm.value?.quantity,
//     currentForm.value?.stock_name,
//     currentForm.value?.product_spec,
//   ],
//   () => {
//     // 强制重新计算 availableStock
//     nextTick(() => {
//       if (currentForm.value?.quantity) {
//         const max = availableStock.value;
//         if (Number(currentForm.value.quantity) > max) {
//           currentForm.value.quantity = max;
//           toast.value?.show({
//             type: "warning",
//             message: `数量不能超过可用库存${max}`,
//           });
//         }
//       }
//     });
//   },
//   { deep: true }
// );
// 当前表单
const currentForm = computed(() => {
  console.log(
    formData.value.forms,
    "formData.forms[currentDateIndex.value]==currentForm="
  );
  console.log(currentDateIndex.value, "currentDateIndex.value==currentForm=");
  console.log(isEdit.value, "====isEdit.value=====");
  const form = formData.value.forms[currentDateIndex.value] || ref(getEmptyForm());
  return form;
});
// 获取当前产品的库存信息
const getCurrentStockInfo = computed(() => {
  if (!currentForm.value?.stock_name || !currentForm.value?.product_spec) {
    return null;
  }

  const stockKey = `${currentForm.value.stock_name}-${currentForm.value.product_spec}`;
  const stockInfo = stockUsageMap.value.get(stockKey);

  if (!stockInfo) return null;

  return {
    totalStock: stockInfo.totalStock,
    used: stockInfo.used,
    remaining: stockInfo.totalStock - stockInfo.used,
    forms: stockInfo.forms,
  };
});
// 剩余金额
const remainingAmount = computed(() => {
  const total = Number(currentForm.value.amount) || 0;
  const initial = Number(currentForm.value.paid_amount) || 0;
  return (total - initial).toFixed(2);
});

// 模态框配置
const modalConfig = reactive({
  title: "",
  content: "",
  action: "",
});

// 表单验证规则
const formRules = {
  customer_name: {
    required: true,
    message: "请输入客户姓名",
    trigger: ["blur", "change"],
  },
  stock_ids: {
    required: true,
    message: "请选择产品",
    trigger: ["blur", "change"],
  },
  quantity: [
    {
      required: true,
      message: "请输入数量",
      trigger: ["blur", "change"],
    },
    {
      validator: (rule, value, callback) => {
        if (value && (!isNumber(value) || Number(value) <= 0)) {
          callback(new Error("请输入有效的数量"));
        } else {
          callback();
        }
        if (
          value &&
          Number(value) > Number(currentForm.value.manufacturers.totalQuantity)
        ) {
          callback(new Error("数量不能大于库存！"));
        } else {
          callback();
        }
      },
      trigger: ["blur", "change"],
    },
  ],
  unit_price: [
    {
      required: true,
      message: "请输入单价",
      trigger: ["blur", "change"],
    },
    {
      validator: (rule, value, callback) => {
        if (value && (!isNumber(value) || Number(value) < 0)) {
          callback(new Error("请输入有效的单价"));
        } else {
          callback();
        }
      },
      trigger: ["blur", "change"],
    },
  ],
  // cost_price: [{
  // 		required: true,
  // 		message: "请输入进价",
  // 		trigger: ["blur", "change"],
  // 	},
  // 	{
  // 		validator: (rule, value, callback) => {
  // 			if (value && (!isNumber(value) || Number(value) < 0)) {
  // 				callback(new Error("请输入有效的进价"));
  // 			} else {
  // 				callback();
  // 			}
  // 		},
  // 		trigger: ["blur", "change"],
  // 	},
  // ],
  customer_phone: {
    validator: (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("请输入有效的手机号码"));
      } else {
        callback();
      }
    },
    trigger: ["blur", "change"],
  },
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return "";
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`; // 确保格式为 YYYY-MM-DD
};

// 数字验证
const isNumber = (value) => {
  return !isNaN(parseFloat(value)) && isFinite(value);
};

// 监听表单变化自动计算金额和同步基本信息
watch(
  () => [
    currentForm.value?.quantity,
    currentForm.value?.unit_price,
    currentForm.value?.cost_price,
  ],
  () => {
    calculateAmounts();
  }
);
watch(
  () => [currentForm.value?.quantity],
  () => {
    if (currentForm.value?.stock_name) {
      handleInventoryChange(); // 更新库存
    }
  }
);

// 监听基本信息变化，同步到其他日期表单
watch(
  () => [
    // currentForm.value?.vehicle_number,
    currentForm.value?.delivery_destination,
    currentForm.value?.customer_name,
    currentForm.value?.customer_phone,
    currentForm.value?.unit,
  ],
  () => {
    if (formData.value.forms.length > 1) {
      // 获取当前表单的基本信息（不包含规格、汇款状态和价格信息）
      const {
        // vehicle_number,
        delivery_destination,
        customer_name,
        customer_phone,
        unit,
      } = currentForm.value;

      // 同步到其他日期的表单
      formData.value.forms.forEach((form, index) => {
        if (index !== currentDateIndex.value) {
          // form.vehicle_number = vehicle_number;
          form.delivery_destination = delivery_destination;
          form.customer_name = customer_name;
          form.customer_phone = customer_phone;
          form.unit = unit;
        }
      });
    }
  },
  {
    deep: true,
  }
);

// 切换日期标签时的处理
const handleTabsChange = (item) => {
  if (item.index >= 0 && item.index < formData.value.dates.length) {
    // 保存当前表单的基本信息（不包含汇款状态和价格信息）
    const currentBasicInfo = {
      // vehicle_number: currentForm.value.vehicle_number,
      delivery_destination: currentForm.value.delivery_destination,
      customer_name: currentForm.value.customer_name,
      customer_phone: currentForm.value.customer_phone,
      // product_spec: currentForm.value.product_spec, // 不需要同步
      unit: currentForm.value.unit,
    };

    // 切换到新的日期
    currentDateIndex.value = item.index;

    // 如果新表单是空的，填充基本信息
    if (formData.value.forms[item.index]) {
      const targetForm = formData.value.forms[item.index];
      if (!targetForm.customer_name) {
        Object.assign(targetForm, currentBasicInfo);
      }
    }
  }
};

const eventDateHandle = async (eType, eData) => {
  console.log(eType, eData, "==eventDateHandle===");
  switch (eType) {
    case "handleSubmit":
      // 提交处理
      if (isSubmitting.value) return;
      if (!formData.value.dates.length) {
        return toast.value?.show({
          type: "warning",
          message: "请选择日期",
        });
      }

      const isValid = await validateForm();
      console.log(isValid, "isValid===");
      if (!isValid) return;

      modalConfig.title = "确认提交";
      modalConfig.content = `确定要${isEdit.value ? "更新" : "提交"}这些订单吗？`;
      modalConfig.action = "submit";
      modal.value?.open();
      break;

    case "handleDelete": //删除处理
      modalConfig.title = "确认撤销";
      modalConfig.content = "确认撤销吗？该操作会重新计入库存！";
      modalConfig.action = "delete";
      modal.value?.open();
      break;

    case "open":
      calendar.value.open();
      break;

    case "pickerProductSpecConfirm": // 处理规格选择确认
      const selectedSpec = eData.value[0];
      // 只更新当前日期表单的product_spec字段
      if (formData.value.forms[currentDateIndex.value]) {
        formData.value.forms[currentDateIndex.value].product_spec = selectedSpec;
      }
      pickerRef.value?.close();
      break;
    case "pickerProductSpecCancel": // 处理规格选择取消
      pickerRef.value?.close();
      break;
    case "pickerProductSpecOpen": // 处理规格选择取消
      pickerRef.value?.open();
      break;
    case "pickerStockIdsOpen": // 处理产品选择取消
      pickerRef.value?.open();
      break;
    case "pickerStockIdsConfirm": // 处理产品选择确认
      const selectedStock = eData.value[0];
      if (formData.value.forms[currentDateIndex.value]) {
        formData.value.forms[currentDateIndex.value].stock_name =
          selectedStock?.manufacturer || "";
        formData.value.forms[currentDateIndex.value].product_spec =
          selectedStock?.specification;
        formData.value.forms[currentDateIndex.value].unit = selectedStock?.unit;
        formData.value.forms[currentDateIndex.value].manufacturers = selectedStock;
        formData.value.forms[currentDateIndex.value].quantity = 0;
        // manufacturerGroupList.value?.find(item=>item.manufacturer===selectedStock.manufacturer)
        console.log(currentForm.value, "currentForm");
        // 更新库存使用 Map
        const stockKey = `${selectedStock.manufacturer}-${selectedStock.specification}`;
        if (!stockUsageMap.value.has(stockKey)) {
          stockUsageMap.value.set(stockKey, {
            totalStock: selectedStock.totalRemainingQuantity,
            used: 0,
            forms: new Set(),
          });
        }

        // 将当前表单添加到跟踪列表
        stockUsageMap.value.get(stockKey).forms.add(currentDateIndex.value);
      }
      pickerRef.value?.close();
      break;
    case "pickerStockIdsCancel": // 处理产品选择取消
      pickerRef.value?.close();
      break;
    case "tabsChange":
      handleTabsChange(eData);
      break;
    case "confirm":
      const dates = eData;
      if (!dates?.length) return;

      formData.value.dates = dates.map((date) => {
        return {
          name: formatDate(date),
        };
      });

      // 保持现有表单数据
      const existingForms = [...formData.value.forms];
      const firstForm = existingForms[0] || ref(getEmptyForm());

      // 获取基本信息（不包含汇款状态和价格信息）
      const basicInfo = {
        // vehicle_number: firstForm.vehicle_number,
        delivery_destination: firstForm.value.delivery_destination,
        customer_name: firstForm.value.customer_name,
        customer_phone: firstForm.value.customer_phone,
        // product_spec: firstForm.product_spec, // 不包含规格信息
        unit: firstForm.value.unit || defaultUnit,
      };

      formData.value.forms = formData.value.dates.map((dateObj) => {
        const existingForm = existingForms.find((form) => form.date === dateObj.name);
        if (existingForm) {
          return existingForm;
        } else {
          // 新表单继承基本信息，但价格信息和汇款状态保持独立
          return {
            ...getEmptyForm(),
            ...basicInfo,
            date: dateObj.name,
            status: 0, // 新表单默认未付款
            paid_amount: 0,
          };
        }
      });

      currentDateIndex.value = 0;
      break;
    default:
      break;
  }
};

// 支付状态变更
const handlePaymentStatusChange = (value) => {
  uni.showModal({
    title: "确认提示",
    content: value === 2 ? "确定已经收到全部款项了吗？" : "确定要标记为未收款吗？",
    success: (res) => {
      if (res.confirm) {
        // 只更新当前日期的支付状态
        currentForm.value.status = value;
        if (value === 2) {
          // 已付清
          currentForm.value.paid_amount = currentForm.value.amount;
        } else if (value === 0) {
          // 未付款
          currentForm.value.paid_amount = 0;
        }
      } else {
        // 恢复原状态
        currentForm.value.status = value === 2 ? 0 : 2;
      }
    },
  });
};

// 修改 handleInventoryChange 函数来使用 Map
const handleInventoryChange = () => {
  // 遍历所有库存记录并更新使用量
  stockUsageMap.value.forEach((stockInfo, stockKey) => {
    let totalUsed = 0;

    // 计算该产品在所有表单中的使用量
    formData.value.forms.forEach((form, index) => {
      const formStockKey = `${form.stock_name}-${form.product_spec}`;
      if (formStockKey === stockKey) {
        totalUsed += Number(form.quantity) || 0;
      }
    });

    // 更新使用量
    stockInfo.used = totalUsed;

    // 更新所有相关表单的可用库存
    stockInfo.forms.forEach((formIndex) => {
      const form = formData.value.forms[formIndex];
      if (form) {
        form.manufacturers = {
          ...form.manufacturers,
          totalRemainingQuantity:
            stockInfo.totalStock - totalUsed + (Number(form.quantity) || 0),
        };
      }
    });
  });

  console.log(stockUsageMap.value, "====stockUsageMap.value===");
};

// 计算金额
const calculateAmounts = () => {
  const quantity = Number(currentForm.value.quantity) || 0;
  const unitPrice = Number(currentForm.value.unit_price) || 0;
  const costPrice = Number(currentForm.value.cost_price) || 0;

  currentForm.value.amount = (quantity * unitPrice).toFixed(2);
  currentForm.value.payable_amount = (quantity * unitPrice).toFixed(2);
  currentForm.value.net_profit = (quantity * (unitPrice - costPrice)).toFixed(2);
};

// 验证表单
const validateForm = async (fn) => {
  if (!formRef.value) return false;

  console.log(formRef.value, "form.value==validateForm=");
  console.log(formData.value.forms, "formData.forms==validateForm=");
  console.log(currentDateIndex.value, "currentDateIndex.value==validateForm=");
  console.log(currentForm.value, "currentForm.value==validateForm=");

  try {
    if (onLoadOption.value.type === "add") {
      // 先验证当前表单
      // await formRef.value.validate();
    }

    // 验证所有日期的表单
    const errors = [];
    // 修改库存检查逻辑
    const insufficientStocks = [];
    for (const [stockKey, stockInfo] of stockUsageMap.value.entries()) {
      const [manufacturer, spec] = stockKey.split("-");
      const remaining = stockInfo.totalStock - stockInfo.used;

      if (remaining < 0) {
        insufficientStocks.push({
          manufacturer,
          specification: spec,
          unit: currentForm.value.unit,
          quantity: Math.abs(remaining), // 转为正数
          remainingQuantity: Math.abs(remaining), // 转为正数
          status: 0,
          isInStock: true, // 库存不足默认了 已经入库，原因：生成出库的时候，查询的 入库的入库单，所以暂时这样，
          unitPrice: currentForm.value.unit_price,
          isDel: 0,
          createTime: new Date().getTime(),
        });
      }
    }

    if (insufficientStocks.length > 0) {
      // 构建提示信息
      const stocksMessage = insufficientStocks
        .map((item) => `（${item.manufacturer} ${item.specification}）`)
        .join("\n");

      const result = await uni.showModal({
        title: "提交库存不足提示",
        content: `以下产品库存不足：\n${stocksMessage}\n是否继续提交？此操作会生成对应的入库单！确定要${
          isEdit.value ? "更新" : "提交"
        }这些订单吗？`,
        showCancel: true,
      });

      console.log(result, "result===");
      // 等待用户确认
      if (!result.confirm) {
        return false;
      } else {
        console.log(insufficientStocks, "===insufficientStocks====");

        debugger;
        let res = await handleSubmitConfirm("inStock", insufficientStocks);
        if (res.code === 0) {
          notify.value?.show({
            type: "success",
            message: res.message,
          });
          setTimeout(() => {
            uni.navigateBack({ delta: 1 });
          }, 1500);
        } else {
          notify.value?.show({
            type: "error",
            message: res.message,
          });
        }

        return false;
      }
    }
    // 校验规则封装
    const validateField = (formItem, field, message, validator = null) => {
      if (!formItem[field] || (validator && !validator(formItem[field]))) {
        errors.push({
          date: formItem.date,
          field,
          message,
        });
      }
    };

    // 格式校验封装（可根据需要自定义）
    const isValidString = (value) => typeof value === "string" && value.trim().length > 0;
    const isPositiveNumber = (value) => !isNaN(value) && Number(value) > 0;
    const isNonNegativeNumber = (value) => !isNaN(value) && Number(value) >= 0;

    let stockNameError = {};
    for (const formItem of formData.value.forms) {
      if (onLoadOption.value.type === "add") {
        // 跳过当前表单（因为当前表单已在前面验证）
        // if (index === currentDateIndex.value) return;
      }

      // 具体字段校验
      await validateField(formItem, "customer_name", "客户姓名未填写", isValidString);

      await validateField(formItem, "stock_name", "产品未选择", isValidString);

      await validateField(formItem, "quantity", "数量未正确填写", isPositiveNumber);

      await validateField(
        formItem,
        "quantity",
        "数量不能大于剩余库存！",
        (value) =>
          !isNaN(value) &&
          !isNaN(formItem?.manufacturers?.totalRemainingQuantity) &&
          Number(value) <= Number(formItem?.manufacturers?.totalRemainingQuantity)
      );

      await validateField(formItem, "unit_price", "单价未正确填写", isNonNegativeNumber);
      // 验证 多时间选择同产品 库存问题处理
      // 判断key 是否存在
      if (stockNameError[formItem.stock_name]) {
        stockNameError[formItem.stock_name] += Number(formItem.quantity);
      } else {
        stockNameError[formItem.stock_name] = Number(formItem.quantity);
      }
    }

    console.log(stockNameError, "stockNameError==validateForm=");
    // manufacturerGroupList
    // manufacturerGroupList.value.forEach((item) => {
    //   if (stockNameError[item.manufacturer]) {
    //     if (stockNameError[item.manufacturer] > item.totalRemainingQuantity) {
    //       errors.push({
    //         date: item.manufacturer,
    //         field: "stock_name",
    //         message: `库存不足，剩余库存${item.totalRemainingQuantity}吨`,
    //       });
    //     }
    //   }
    // });

    console.log(errors, "errors==validateForm=");

    if (errors.length > 0) {
      // 按日期和字段进行排序，优先显示最早的错误
      errors.sort((a, b) => {
        if (a.date !== b.date) {
          return a.date.localeCompare(b.date);
        }
        return a.field.localeCompare(b.field);
      });

      // 显示第一个错误
      const firstError = errors[0];
      if (!toast.value?.isShowing) {
        toast.value?.show({
          type: "error",
          message: `${firstError.date} ${firstError.message}`,
        });
      }

      // 切换到对应的错误日期
      const errorIndex = formData.value.dates.findIndex(
        (date) => date.name === firstError.date
      );
      if (errorIndex !== -1) {
        currentDateIndex.value = errorIndex;
      }

      return false;
    }

    return true;
  } catch (error) {
    console.log(error, "catch==error==validateForm=");
    // 捕获表单级别的验证错误
    const errorMessage = error.errors?.[0]?.message || "表单验证失败";
    const currentDate = formData.value.dates[currentDateIndex.value]?.name;

    if (!toast.value?.isShowing) {
      toast.value?.show({
        type: "error",
        message: currentDate ? `${currentDate} ${errorMessage}` : errorMessage,
      });
    }

    return false;
  }
};

// 模态框确认
const handleModalConfirm = async () => {
  if (isSubmitting.value) return;
  isSubmitting.value = true;

  console.log("模态框确认 handleModalConfirm");
  try {
    uni.showLoading({
      title: modalConfig.action === "delete" ? "正在撤销..." : "正在提交...",
      mask: true,
    });

    let res = null;
    if (modalConfig.action === "delete") {
      const currentForm = formData.value.forms[currentDateIndex.value];
      if (!currentForm) throw new Error("未找到要撤销的记录");

      console.log(currentForm, "====currentForm====currentForm====currentForm");
      console.log(
        currentForm.user_id,
        currentForm._id,
        "====currentForm====currentForm====currentForm"
      );
      // 删除
      // const data = {
      //   ...currentForm,
      //   isDel: 1,
      // };
      // Reflect.deleteProperty(data, "_id");
      // res = await uniCloudSalesManager.updateSalesRecord(currentForm._id, data);
      // // 处理删除响应
      // if (res.code === 0) {
      //   notify.value?.show({
      //     type: "success",
      //     message: "删除成功",
      //   });
      //   setTimeout(() => {
      //     uni.navigateBack({
      //       delta: 1,
      //     });
      //   }, 1500);
      // } else {
      //   throw new Error(res.message || "删除失败");
      // }
      // 撤销
      res = await uniCloudSalesManager.revertOutStock(
        currentForm._id,
        currentForm.user_id
      );
      if (res.code == 0) {
        notifyRef.value.success(res.message);
        paging?.value?.reload();
      } else {
        notifyRef.value.error(res.message);
      }
    } else {
      res = await handleSubmitConfirm();
      if (res.code === 0) {
        notify.value?.show({
          type: "success",
          message: res.message,
        });
        setTimeout(() => {
          uni.navigateBack({ delta: 1 });
        }, 1500);
      } else {
        notify.value?.show({
          type: "error",
          message: res.message,
        });
      }
    }
  } catch (error) {
    console.error("Operation error:", error);
    notify.value?.show({
      type: "error",
      message: `${
        modalConfig.action === "delete" ? "撤销" : isEdit.value ? "更新" : "提交"
      }失败：${error.message || "未知错误"}`,
    });
  } finally {
    uni.hideLoading();
    isSubmitting.value = false;
  }
};

// 提交确认
// const handleSubmitConfirm = async () => {
//   const userInfo = uni.getStorageSync("userInfo");

//   const promises = formData.value.forms.map((form) => {
//     const submitData = JSON.parse(JSON.stringify(form));
//     // {
//     //   ...form,
//     // };
//     // 确保数值字段为数字类型
//     submitData.quantity = Number(form.quantity) || 0;
//     submitData.unit_price = Number(form.unit_price) || 0;
//     submitData.cost_price = Number(form.cost_price) || 0;
//     submitData.amount = Number(form.amount) || 0;
//     submitData.payable_amount = Number(form.payable_amount) || 0;
//     submitData.paid_amount = Number(form.paid_amount) || 0;
//     submitData.net_profit = Number(form.net_profit) || 0;

//     submitData.user_id = userInfo._id;

//     console.log(submitData, "==提交的=submitData===");
//     if (isEdit.value) {
//       Reflect.deleteProperty(submitData, "_id");
//       return uniCloudSalesManager.updateSalesRecord(form._id, submitData);
//     } else {
//       return uniCloudSalesManager.addSalesRecord(submitData);
//     }
//   });

//   return await Promise.all(promises);
// };
// 提交确认 生成 销售记录
const handleSubmitConfirm = async (type, cData) => {
  const userInfo = uni.getStorageSync("userInfo");

  // 库存不足生成入库单
  if (type == "inStock") {
    // 生成入库单（可以处理多个产品）
    let dataList = cData.map((item) => {
      return {
        ...item,
        date: new Date().getTime(),
        updateTime: new Date().getTime(),
        userId: userInfo._id,
      };
    });
    console.log(dataList, "====dataList=======");

    let res = await uniCloudStockManager.addInStockRecords(dataList);
    if (res.code != 0) {
      notify.value?.show({
        type: "error",
        message: res.message,
      });
      return res;
    }
  }
  let dataList = formData.value.dates.map((date, index) => {
    const form = formData.value.forms[index];
    return {
      ...form,
      date: date.name,
      quantity: Number(form.quantity) || 0,
      unit_price: Number(form.unit_price) || 0,
      cost_price: Number(form.cost_price) || 0,
      amount: Number(form.amount) || 0,
      payable_amount: Number(form.payable_amount) || 0,
      paid_amount: Number(form.paid_amount) || 0,
      net_profit: Number(form.net_profit) || 0,
      user_id: userInfo._id,
    };
  });

  let res = await uniCloudSalesManager.generateStockOutRecord(dataList, userInfo._id);

  return res;
};

// 加载编辑数据
const loadEditData = async (id) => {
  try {
    uni.showLoading({
      title: "加载中...",
      mask: true,
    });

    const res = await uniCloudSalesManager.getSalesRecordById(id);

    if (!res.code && res.data) {
      const data = res.data;
      // 确保数值字段类型正确
      data.quantity = Number(data.quantity) || 0;
      data.cost_price = Number(data.cost_price) || 0;
      data.cost_price = Number(data.cost_price) || 0;
      data.amount = Number(data.amount) || 0;
      data.payable_amount = Number(data.payable_amount) || 0;
      data.paid_amount = Number(data.paid_amount) || 0;
      data.net_profit = Number(data.net_profit) || 0;

      formData.value.dates = [data.date];
      formData.value.forms = [data];
      currentForm.value = data;
    } else {
      throw new Error(res.message || "加载数据失败");
    }
  } catch (error) {
    console.error("Load data error:", error);
    toast.value?.show({
      type: "error",
      message: `加载失败：${error.message || "未知错误"}`,
    });
  } finally {
    uni.hideLoading();
  }
};
// 页面加载
onLoad((option) => {
  onLoadOption.value = option;

  if (option.id) {
    isEdit.value = option.id;
    loadEditData(option.id);
  }
});

const getInit = async () => {
  const userInfo = uni.getStorageSync("userInfo");
  const res = await uniCloudStockManager.getManufacturerGroupList(userInfo._id);
  console.log(res, "=getGroupList=res==res==res");
  manufacturerGroupList.value = res.data.map((item) => {
    item.label = item.manufacturer + " " + item.specification;
    return item;
  });
  if (!manufacturerGroupList?.value?.length) {
    nextTick(() => {
      console.log(notify.value, "====notify.value====");
      notify.value?.show({
        type: "error",
        message: `没有库存可以出库！3秒后回到首页`,
      });
    });
    setTimeout(() => {
      uni.navigateBack({
        delta: 1,
      });
    }, 1500);
  } else {
    if (onLoadOption?.value?.type == "add") {
      nextTick(() => {
        console.log("打开日历", calendar.value);
        calendar.value.open(); // 打开日历
      });
    }
  }

  console.log(manufacturerGroupList.value, "==manufacturerGroupList===");
};
// 页面挂载

onMounted(() => {
  console.log("onMounted", calendar.value);
  console.log("onLoadOption", onLoadOption.value);
  getInit();
});
// 页面卸载
onUnload(() => {
  // 清理工作
  formData.value.dates = [];
  formData.value.forms = [];
  currentDateIndex.value = 0;
  isSubmitting.value = false;
});
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  background-color: #f8f8f8;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.content-wrapper {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
  padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
  /* 为底部按钮预留空间 */
}

.selected-dates {
  display: flex;
  align-items: center;

  .label {
    font-size: 28rpx;
    color: #666;
    margin-right: 10rpx;
  }

  .value {
    font-size: 28rpx;
    color: #333;
    flex: 1;
  }
}

.date-tabs {
  white-space: nowrap;
  padding: 10rpx;
  background-color: #fff;
  border-radius: 8rpx;

  .date-tabs-content {
    display: inline-flex;
    padding: 0 10rpx;

    .date-tab-btn {
      margin-right: 20rpx;

      &:last-child {
        margin-right: 0;
      }
    }
  }
}

.input-prefix,
.input-suffix {
  font-size: 28rpx;
  color: #666;
  padding: 0 10rpx;
}

.footer-buttons {
  padding: 30rpx 20rpx calc(30rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;
  width: 100%;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 99;
  box-shadow: 0 -2rpx 20rpx rgba(0, 0, 0, 0.05);
  display: flex;

  .button-group {
    display: flex;
    align-items: center;
    justify-content: space-between;
    max-width: 900rpx;
    margin: 0 auto;
    flex: 1;

    .button-wrapper {
      flex: 1;

      :deep(.uv-button-wrapper) {
        width: 100%;
      }
    }
  }
}

.add-icon {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;

  .add-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 20rpx;

    .icon-wrapper {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      background: rgba(41, 121, 255, 0.1);
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s ease;
      cursor: pointer;

      &:active {
        transform: scale(0.95);
        background: rgba(41, 121, 255, 0.2);
      }
    }

    .add-text {
      font-size: 28rpx;
      color: #666;
      margin-top: 10rpx;
    }
  }
}

.date-select-area {
  background: #fff;
  padding: 30rpx 20rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  .date-info {
    display: flex;
    align-items: center;
    gap: 12rpx;

    .date-label {
      font-size: 28rpx;
      color: #666;
    }

    .date-count {
      background: rgba(41, 121, 255, 0.1);
      color: #2979ff;
      padding: 4rpx 16rpx;
      border-radius: 20rpx;
      font-size: 24rpx;
      font-weight: 500;
    }
  }

  .button-content {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.form-card {
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  .card-title {
    display: flex;
    align-items: center;
    margin: -24rpx -24rpx 20rpx;
    padding: 24rpx;
    background: linear-gradient(
      to right,
      rgba(41, 121, 255, 0.05),
      rgba(41, 121, 255, 0)
    );
    position: relative;

    &::before {
      content: "";
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6rpx;
      height: 32rpx;
      background: #2979ff;
      border-radius: 0 4rpx 4rpx 0;
    }

    .icon-wrapper {
      width: 64rpx;
      height: 64rpx;
      border-radius: 16rpx;
      background: rgba(41, 121, 255, 0.1);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 16rpx;
    }

    text {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-left: 16rpx;
      letter-spacing: 1rpx;
    }
  }

  &.summary-card {
    :deep(.uv-cell) {
      padding: 24rpx 0;

      &:not(:last-child) {
        border-bottom: 2rpx solid #f5f5f5;
      }
    }
  }
}

.spec-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 44rpx;
  padding: 4rpx 0;

  .placeholder {
    color: #999;
    font-size: 28rpx;
  }
}

.tabs-wrapper {
  background: #fff;
  padding: 0 20rpx;
  border-bottom: 2rpx solid #f5f5f5;

  .payment-status {
    padding: 10rpx 0;
    margin-top: -10rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    :deep(.uv-form-item) {
      margin-bottom: 0;
      padding: 6rpx 0;
    }
  }
}
.stock-usage-info {
  background-color: #f8f8f8;
  border-radius: 8rpx;
  padding: 16rpx;
  margin-bottom: 20rpx;

  .stock-usage-item {
    display: flex;
    align-items: center;
    margin-bottom: 8rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      color: #666;
      font-size: 26rpx;
      min-width: 140rpx;
    }

    .value {
      color: #333;
      font-size: 26rpx;
      font-weight: 500;

      &.warning {
        color: #ff9900;
      }

      &.danger {
        color: #ff4d4f;
      }
    }
  }
}
</style>
